package com.saifan.wyy_ov.ui.onlishop;

import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.ListPopupWindow;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.BaseActivity;
import com.saifan.wyy_ov.common.IconText;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.GoodsDetailBean;
import com.saifan.wyy_ov.data.bean.MyCartBean;
import com.saifan.wyy_ov.data.bean.MyCartBean.ShoppingCartDetail;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;


import com.saifan.wyy_ov.ui.view.Picker;
import com.saifan.wyy_ov.ui.zoomimage.ZoomImageActivity;
import com.saifan.wyy_ov.utils.CallPhoneUtil;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import cn.lightsky.infiniteindicator.InfiniteIndicatorLayout;
import cn.lightsky.infiniteindicator.slideview.BaseSliderView;
import cn.lightsky.infiniteindicator.slideview.DefaultSliderView;
import cn.lightsky.infiniteindicator.slideview.TextSliderView;
import lomasky.ma.utils.DensityUtil;

/**
 * @author WangLi
 * @version V1.0
 * @date 2015年3月17日 上午11:02:40
 * @Description 商品详情页面
 */

public class GoodsDetailActivity extends BaseActivity implements OnClickListener, BaseSliderView.OnSliderClickListener {
    //private ViewPager photos;
    //private TextView goodsName;
    //private TextView goodsIndicator;
    private TextView price;
    private Button addGouwuche;
    private Button qianggou;
    private TextView delivery;
    private TextView deliveryNote;
    private TextView sales;
    private TextView goodsNote;
    private TextView storeComment;
    private TextView storeName;
    private TextView storeAddress;
    private TextView time;
    private Button tel;
    private RelativeLayout loadingLayout;
    private IGetData getData;
    private String storeId;// 店铺ID
    private String goodsId;// 商品ID
    private String goodsNameString;// 商品名
    private String priceString;// 商品价格
    private CommonDataBean requestBean;
    private GoodsDetailBean goodsDetailBean;

    private List<GoodsDetailBean.Photos> photosList;
    private List<View> views;
    private MyCartBean myCartBean;
    private Dialog dialog;
    private InfiniteIndicatorLayout slider;
    private ListPopupWindow listPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        findViews();
        initPopList();
        storeId = getIntent().getStringExtra("storeId");
        goodsId = getIntent().getStringExtra("goodsId");
        goodsNameString = getIntent().getStringExtra("goodsName");
        priceString = getIntent().getStringExtra("price");
        requestBean = new CommonDataBean();
        requestBean.setID(Integer.valueOf(goodsId));
        requestBean.setStoreId(storeId);
        requestBean.setPage(0);
        getData = new GetData();
        getDataInit();
        setEnabledNavigation(true);

    }

    private void initPopList() {
        listPopupWindow = new ListPopupWindow(this);
        lomasky.ma.xui.CommonAdapter adapter = new lomasky.ma.xui.CommonAdapter<IconText>(this, R.layout.pop_item) {
            @Override
            public void onBind(lomasky.ma.xui.ViewHolderHelper holder, IconText iconText, int i) {
                holder.setImage(R.id.pop_img, iconText.icon);
                holder.setText(R.id.pop_text, iconText.text);
            }
        };
        List<IconText> list = new ArrayList<>();
        list.add(new IconText(R.mipmap.home_insidepage, "商城首页"));
        list.add(new IconText(R.mipmap.cart_insidepage, "我的购物车"));
        list.add(new IconText(R.mipmap.indent_insidepage, "我的订单"));
        list.add(new IconText(R.mipmap.collect_insidepage, "我的收藏"));
        adapter.setData(list);

        listPopupWindow.setAdapter(adapter);
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = null;
                switch (position) {
                    case 0:
                        intent = new Intent(getBaseContext(), OnlineShopActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        break;
                    case 1:
                        intent = new Intent(getBaseContext(), MyCartActivity.class);
                        break;
                    case 2:
                        intent = new Intent(getBaseContext(), MyOrderActivity.class);
                        break;
                    case 3:
                        intent = new Intent(getBaseContext(), MyCollectActivity.class);
                        break;
                    default:
                        break;
                }
                listPopupWindow.dismiss();
                if (intent != null) {
                    startActivity(intent);
                }


            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.store_details, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_more) {
            listPopupWindow.setAnchorView(mToolbar);
            listPopupWindow.setWidth(DensityUtil.getWidth(this) / 2);
            listPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            listPopupWindow.setHorizontalOffset(DensityUtil.getWidth(this) / 2);
            listPopupWindow.show();
        }
        return super.onOptionsItemSelected(item);
    }

    private void findViews() {
        slider = (InfiniteIndicatorLayout) findViewById(R.id.slider);
        loadingLayout = (RelativeLayout) findViewById(R.id.loading_lay);
//		photos = (ViewPager) findViewById(R.id.photos);
//		goodsName = (TextView) findViewById(R.id.goods_name);
//		goodsIndicator = (TextView) findViewById(R.id.goods_indicator);
        price = (TextView) findViewById(R.id.price);
        addGouwuche = (Button) findViewById(R.id.add_gouwuche);
        qianggou = (Button) findViewById(R.id.qianggou);
        delivery = (TextView) findViewById(R.id.delivery);
        deliveryNote = (TextView) findViewById(R.id.delivery_note);
        sales = (TextView) findViewById(R.id.sales);
        goodsNote = (TextView) findViewById(R.id.goods_note);
        storeComment = (TextView) findViewById(R.id.store_comment);
        storeName = (TextView) findViewById(R.id.store_name);
        storeAddress = (TextView) findViewById(R.id.store_address);
        time = (TextView) findViewById(R.id.time);
        tel = (Button) findViewById(R.id.tel);

        addGouwuche.setOnClickListener(this);
        qianggou.setOnClickListener(this);
        storeComment.setOnClickListener(this);
        tel.setOnClickListener(this);
    }

    public void onClick(View v) {
        if (v == addGouwuche) {
            // Handle clicks for addGouwuche
            if (getRoomInfoBean().getUserType() == 2) {
                for (PermissionsBean permissionsBean : getPermissions()) {
                    if (permissionsBean.getYKQX_GNMC().equals("在线商城")) {
                        showPop();
                        return;
                    }
                }
                ToastUtil.showToast(GoodsDetailActivity.this, "您的权限不能进行此操作");
                return;
            } else if (getRoomInfoBean().getUserType() == 3) {
                ToastUtil.showToast(GoodsDetailActivity.this, "您的权限不能进行此操作");
                return;
            }
            showPop();
        } else if (v == qianggou) {
            if (getRoomInfoBean().getUserType() == 2) {
                for (PermissionsBean permissionsBean : getPermissions()) {
                    if (permissionsBean.getYKQX_GNMC().equals("在线商城")) {
                        goBuy();
                        return;
                    }
                }
                ToastUtil.showToast(GoodsDetailActivity.this, "您的权限不能进行此操作");
                return;
            } else if (getRoomInfoBean().getUserType() == 3) {
                ToastUtil.showToast(GoodsDetailActivity.this, "您的权限不能进行此操作");
                return;
            }
            goBuy();
        } else if (v == storeComment) {
            Intent intent = new Intent(GoodsDetailActivity.this, CommentsActivity.class);
            intent.putExtra("ID", Integer.valueOf(storeId));
            startActivity(intent);
        } else if (v == tel) {
//
            call();
        }
    }


    // 联系买家
    public void call() {


        if (!StringUtil.isNullOrEmpty(goodsDetailBean.getTel())) {


            if (Build.VERSION.SDK_INT >= 23) {

                int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(GoodsDetailActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                    return;
                } else {
                    CallPhoneUtil.callPhone(GoodsDetailActivity.this, goodsDetailBean.getTel());


                }
            } else {

                CallPhoneUtil.callPhone(GoodsDetailActivity.this, goodsDetailBean.getTel());

            }


        }

    }


    private static final int CALL_PHONE = 123;

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                CallPhoneUtil.callPhone(GoodsDetailActivity.this, goodsDetailBean.getTel());


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用拨打电话权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }

    // 立即购买
    public void goBuy() {
        if (goodsDetailBean != null) {
            Intent intent = new Intent(this, SubmitOrderActivity.class);
            //Bundle bundle = new Bundle();
            // 购买类型1为团购
            intent.putExtra("buy_type", 0);
            intent.putExtra("price", Double.valueOf(priceString));
            intent.putExtra("storeId", Integer.valueOf(storeId));
            intent.putExtra("goodsName", goodsNameString);
            intent.putExtra("goodsId", Integer.valueOf(goodsId));
            intent.putExtra("storeName", goodsDetailBean.getStoreName());
            intent.putExtra("maxCount", 999);
            if (photosList != null && !photosList.isEmpty()) {
                intent.putExtra("photo", photosList.get(0).getUrl());
            }
            //  intent.putExtras(bundle);
            startActivity(intent);
        }

    }

    private void getDataInit() {
        getData.getDataJson(GoodsDetailActivity.this, Api.StoreList.GOODSDETAIL, requestBean, "", new ResponseData() {

            @Override
            public void onSuccess(String json) {
                loadingLayout.setVisibility(View.GONE);
                Log.d("zjt",json);
                List<GoodsDetailBean> data = (new Gson()).fromJson(json, new TypeToken<List<GoodsDetailBean>>() {
                }.getType());
                if (data != null && data.size() > 0) {
                    goodsDetailBean = data.get(0);
                    setupViews();
                } else {
                    ToastUtil.showToast(GoodsDetailActivity.this, "暂无商品信息");
                }

            }

            @Override
            public void onFailed(String str) {
            }
        });
    }

    @SuppressLint("InflateParams")
    private void setupViews() {
        if (goodsDetailBean != null) {
            //goodsName.setText(goodsNameString);
            price.setText(PriceUtils.getPrice(priceString) + " 元");
            if (!goodsDetailBean.isIsDelivery()) {
                delivery.setText("不支持送货");
                deliveryNote.setText("");
            } else {
                delivery.setText("支持送货");
                deliveryNote.setText(goodsDetailBean.getDeliveryAmount() + " 元起送 " + goodsDetailBean.getDeliveryInstructions());
            }
            sales.setText("已售" + goodsDetailBean.getSold());
            goodsNote.setText(goodsDetailBean.getGoodsInstruction());
            storeName.setText(goodsDetailBean.getStoreName());
            storeAddress.setText(goodsDetailBean.getAddress());
            if (!StringUtil.isNullOrEmpty(goodsDetailBean.getBusinessDate()) && !StringUtil.isNullOrEmpty(goodsDetailBean.getBusinessTime())) {
                time.setText(goodsDetailBean.getBusinessDate().replace(",", "至") + " " + goodsDetailBean.getBusinessTime().replace(",", "至"));
            }

            tel.setText("联系商家:  " + goodsDetailBean.getTel());
            views = new ArrayList<View>();
            photosList = goodsDetailBean.getGoodsPhotos();
//

            initSlider();

            slider.setVisibility(View.VISIBLE);

        }
    }

    private void initSlider() {
        if (photosList != null && !photosList.isEmpty()) {
            for (int i = 0; i < photosList.size(); i++) {
                urls.add(photosList.get(i).getUrl());
                TextSliderView textSliderView = new TextSliderView(this);
                textSliderView.description(goodsNameString).image(Api.getUrlIp() + photosList.get(i).getUrl()).showImageResForEmpty(R.drawable.pic_none).showImageResForError(R.drawable.pic_load_fail).setScaleType(BaseSliderView.ScaleType.CenterCrop).setOnSliderClickListener(this);
                if (textSliderView.getBundle() != null) {
                    textSliderView.getBundle().putInt("index", i);
                }
                slider.addSlider(textSliderView);
            }
            slider.setIndicatorPosition(InfiniteIndicatorLayout.IndicatorPosition.Center_Bottom);
            if (photosList.size() > 1)
                slider.startAutoScroll(10000);
            else {
                slider.setInfinite(false);
            }


        } else {
            DefaultSliderView defaultSliderView = new DefaultSliderView(this);
            defaultSliderView.image(R.drawable.pic_none).setScaleType(BaseSliderView.ScaleType.CenterCrop);
            slider.addSlider(defaultSliderView);
            slider.setInfinite(false);
        }
    }


    ArrayList<String> urls = new ArrayList<String>();


    // 加入购物车
    private void addCart(int count) {
        myCartBean = new MyCartBean();
        myCartBean.setCustomerID(getRoomInfoBean().getWYKHDA_ZJ());
        myCartBean.setStoreID(Integer.valueOf(storeId));
        List<ShoppingCartDetail> shoppingCartDetails = new ArrayList<ShoppingCartDetail>();
        ShoppingCartDetail mShoppingCartDetail = myCartBean.new ShoppingCartDetail();
        mShoppingCartDetail.setCount(1);
        mShoppingCartDetail.setGoodsID(Integer.valueOf(goodsId));
        mShoppingCartDetail.setStoreID(Integer.valueOf(storeId));
        mShoppingCartDetail.setCount(count);
        shoppingCartDetails.add(mShoppingCartDetail);
        myCartBean.setShoppingCartDetail(shoppingCartDetails);
        getData.getDataJson(GoodsDetailActivity.this, Api.GroupBuy.ADDSHOPPINGCART, myCartBean, "正在请求...", new ResponseData() {

            @Override
            public void onSuccess(String json) {
                ToastUtil.showToast(GoodsDetailActivity.this, "添加成功");
                if (dialog != null || dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onFailed(String str) {
                ToastUtil.showToast(GoodsDetailActivity.this, "添加失败");
            }
        });

    }

    int picker_selected=1;
    @SuppressWarnings("deprecation")
    private void showPop() {
        dialog = new Dialog(GoodsDetailActivity.this, R.style.dialog);
        dialog.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                switch (keyCode) {
                    case 4:
                        dialog.dismiss();
                        return true;
                    default:
                        break;
                }
                return false;
            }
        });
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        Window win = dialog.getWindow();
        win.setContentView(R.layout.pop_add_cart);
        win.setGravity(Gravity.BOTTOM); // 此处可以设置dialog显示的位置
        win.setWindowAnimations(R.style.mystyle);

        final Picker picker = (Picker) win.findViewById(R.id.picker);
        picker_selected=1;
        List<String> picker_strings = new ArrayList<>();
        for (int i = 1; i < 11; i++) {
            picker_strings.add(String.valueOf(i));
        }
        picker.setOnSelectListener(new Picker.onSelectListener() {
            @Override
            public void onSelect(String text) {
                picker_selected=Integer.valueOf(text);
            }
        });
        picker.setData(picker_strings);
        picker.setSelected(0);
        win.findViewById(R.id.add_shopcar).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

//                ToastUtil.showToast(GoodsDetailActivity.this,""+picker_selected);
                addCart(picker_selected);
            }
        });
        // 设置宽度充满屏幕
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = display.getWidth(); // 设置宽度充满屏幕
        win.setAttributes(lp);
    }

    @Override
    public void onSliderClick(BaseSliderView baseSliderView) {
        Intent intent = new Intent(this, ZoomImageActivity.class);
        int position = baseSliderView.getBundle().getInt("index");
        intent.putExtra("position", position);
        intent.putStringArrayListExtra("img", urls);
        startActivity(intent);

    }
}
